package com.car.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.car.bean.BitAutoBrand;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class BitAutoJSON {
	private JSONArray jsonarray;
	private JSONObject jsonObj;

	// 获得JSON的数据
	public String getString(String url) {
		String res = null;
		Document doc = null;
		try {
			doc = Jsoup.connect(url).ignoreContentType(true).get();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return doc.text().split("=")[1];
	}

	// 获得具体品牌的JSON数据地址
	public List<String> getCarInfoUrl(String url) {
		List<String> urls = new ArrayList<>();
		String data = getString(url);
		jsonObj = JSONObject.fromObject(data);
		Set<String> set = jsonObj.keySet();
		Iterator<String> i = set.iterator();
		while (i.hasNext()) {
			JSONObject bit = jsonObj.getJSONObject(i.next());
			int id = bit.getInt("id");
			String link = "http://api.car.bitauto.com/CarInfo/MasterBrandToSerialNew.aspx?type=1&pid=" + id
					+ "&rt=serial&serias=m&key=serial_9_1_m&include=1";
			urls.add(link);
		}
		return urls;
	}

	// 获得具体品牌的信息
	public List<BitAutoBrand> getCarInfo(String url) {
		List<BitAutoBrand> bab = new ArrayList<BitAutoBrand>();
		jsonObj = JSONObject.fromObject(this.getString(url));
		Set<String> set = jsonObj.keySet();
		Iterator<String> i = set.iterator();
		while (i.hasNext()) {
			JSONObject bit = jsonObj.getJSONObject(i.next());
			int bitauto_bbs = bit.getInt("id");
			String bitauto_name = bit.getString("name");
			int bitauto_pid = bit.getInt("pid");
			String bitauto_urlspell = bit.getString("urlSpell");
			String bitauto_showname = bit.getString("showName");
			int bitauto_cssale = bit.getInt("csSale");
			int bitauto_goid = bit.getInt("goid");
			String bitauto_goname = bit.getString("goname");
			int bitauto_rel = 0;
			String bitauto_kbgxsj = null;
			String bitauto_ltgxsj = null;
			BitAutoBrand b = new BitAutoBrand(bitauto_bbs, bitauto_name, bitauto_pid, bitauto_urlspell,
					bitauto_showname, bitauto_cssale, bitauto_goid, bitauto_goname, bitauto_rel, bitauto_kbgxsj,
					bitauto_ltgxsj);
			bab.add(b);
		}
		return bab;
	}

	public static void main(String[] args) {
		BitAutoJSON s = new BitAutoJSON();
		List<String> url = s.getCarInfoUrl(
				"http://api.car.bitauto.com/CarInfo/MasterBrandToSerialNew.aspx?type=1&pid=0&rt=master&serias=m&key=master_0_1_m");
		System.out.println(url.size());
		List<BitAutoBrand> b = s.getCarInfo(
				"http://api.car.bitauto.com/CarInfo/MasterBrandToSerialNew.aspx?type=1&pid=8&rt=serial&serias=m&key=serial_9_1_m&include=1");
		// for (BitAutoBrand bit : b) {
		// System.out.println(bit);
		// }
	}
}
